package com.davinci.servicedesk;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class Incidenten01 extends ListActivity {
	// Progress Dialog
	private ProgressDialog pDialog;

	// Creating JSON Parser object
	JSONDoor jParser = new JSONDoor();

	ArrayList<HashMap<String, String>> productsList;

	// url to get all products list
	private static String url_all_products = "http://servicedesk.dvcicta.nl/app/get_all_klanten.php";

	// JSON Node names
	private static final String TAG_SUCCESS = "success";
	private static final String TAG_KLANTEN = "klanten";
	private static final String TAG_ID = "id";
	private static final String TAG_VOORLETTER = "voorletter";
	private static final String TAG_ACHTERNAAM = "achternaam";
	private static final String TAG_PID = "pid";
	private static final String TAG_PACHTERNAAM = "pachternaam";
	private static final String TAG_PVOORLETTER = "pvoorletter";

	// products JSONArray
	JSONArray klanten = null;

	
	 public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.incidenten01);
	        
			// Hashmap for ListView
			productsList = new ArrayList<HashMap<String, String>>();

			// Loading products in Background Thread
			//new LoadAllProducts().execute();
			new LoadAllProducts().execute();

			// Get listview
			ListView lv = getListView();

			// on seleting single product
			// launching Edit Product Screen
			lv.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					// getting values from selected ListItem
					String pid = ((TextView) view.findViewById(R.id.klantnummer)).getText()
							.toString();
					String pvoorletter = ((TextView) view.findViewById(R.id.voorletter)).getText()
							.toString();
					
					String pachternaam = ((TextView) view.findViewById(R.id.achternaam)).getText()
							.toString();

					// Starting new intent
					Intent in = new Intent(getApplicationContext(),
							Incidenten02.class);
					// sending pid to next activity
					in.putExtra(TAG_PID, pid);
					in.putExtra(TAG_PVOORLETTER, pvoorletter);
					in.putExtra(TAG_PACHTERNAAM, pachternaam);
					
					// starting new activity and expecting some response back
					startActivityForResult(in, 100);
				}
			});
	 }
			/**
			 * Background Async Task to Load all product by making HTTP Request
			 * */
			class LoadAllProducts extends AsyncTask<String, String, String> {

				/**
				 * Before starting background thread Show Progress Dialog
				 * */
				@Override
				protected void onPreExecute() {
					super.onPreExecute();
					pDialog = new ProgressDialog(Incidenten01.this);
					pDialog.setMessage("Bezig met laden van klanten. Een ogenblik geduld a.u.b...");
					pDialog.setIndeterminate(false);
					pDialog.setCancelable(false);
					pDialog.show();
				}

				/**
				 * getting All products from url
				 * */
				protected String doInBackground(String... args) {
					// Building Parameters
					List<NameValuePair> params = new ArrayList<NameValuePair>();
					// getting JSON string from URL
					JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
					
					// Check your log cat for JSON reponse
					Log.d("All Products: ", json.toString());

					try {
						// Checking for SUCCESS TAG
						int success = json.getInt(TAG_SUCCESS);

						if (success == 1) {
							// products found
							// Getting Array of Products
							klanten = json.getJSONArray(TAG_KLANTEN);

							// looping through All Products
							for (int i = 0; i < klanten.length(); i++) {
								JSONObject c = klanten.getJSONObject(i);

								// Storing each json item in variable
								String voorletter = c.getString(TAG_VOORLETTER);
								String achternaam = c.getString(TAG_ACHTERNAAM);
								String id = c.getString(TAG_ID);

								// creating new HashMap
								HashMap<String, String> map = new HashMap<String, String>();

								// adding each child node to HashMap key => value
								map.put(TAG_VOORLETTER, voorletter);
								map.put(TAG_ACHTERNAAM, achternaam);
								map.put(TAG_ID, id);

								// adding HashList to ArrayList
								productsList.add(map);
							}
						} else {
							// no products found
							// Launch Add New product Activity
							Intent i = new Intent(getApplicationContext(),
									KlantenToevoegen.class);
							// Closing all previous activities
							i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							startActivity(i);
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}

					return null;
				}

				/**
				 * After completing background task Dismiss the progress dialog
				 * **/
				protected void onPostExecute(String file_url) {
					// dismiss the dialog after getting all products
					pDialog.dismiss();
					// updating UI from Background Thread
					runOnUiThread(new Runnable() {
						public void run() {
							/**
							 * Updating parsed JSON data into ListView
							 * */
							ListAdapter adapter = new SimpleAdapter(
									Incidenten01.this, productsList,
									R.layout.list_item, new String[] { TAG_VOORLETTER,
											TAG_ACHTERNAAM, TAG_ID},
									new int[] { R.id.voorletter, R.id.achternaam, R.id.klantnummer });
							// updating listview
							setListAdapter(adapter);
						}
					});

	        
	        /*Button next = (Button) findViewById(R.id.volgende);
	        next.setOnClickListener(new View.OnClickListener() {
	            public void onClick(View view) {
	                Intent myIntent = new Intent(view.getContext(), Incidenten02.class);
	                startActivityForResult(myIntent, 0);
	            }
	        });*/
	        Button nieuw_klant = (Button) findViewById(R.id.nieuw_klant);
	        nieuw_klant.setOnClickListener(new View.OnClickListener() {
	            public void onClick(View view) {
	                Intent myIntent = new Intent(view.getContext(), KlantenToevoegen.class);
	                startActivityForResult(myIntent, 0);
	            }
	        });
}
}
	 }
